package com.xiaxiang.xiawan.FunPhoto;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;

import com.dg.acb.utils.configdata.XXConstants;
import com.donggua.aichebao.commonui.photo.DGPhotoViewDlg;
import com.third.share.ShareData;
import com.vondear.rxtools.view.dialog.RxDialogLoading;
import com.vondear.rxtools.view.dialog.RxDialogSureCancel;
import com.vondear.rxtools.view.progressing.style.Wave;
import com.xiaxiang.ar.ARCloud.ARCloudEditor;
import com.okhttp.MyHttpUtils;
import com.xiaxiang.xiawan.FragmentBase;
import com.xiaxiang.xiawan.FunPhoto.Adapter.FunAdapter;
import com.xiaxiang.xiawan.NetBean.BaseNetBean;
import com.xiaxiang.xiawan.NetBean.ErrorNetBean;
import com.xiaxiang.xiawan.NetBean.FunPhotoNetBean;
import com.xiaxiang.xiawan.R;
import com.xiaxiang.xiawan.XXConfigData;
import com.xiaxiang.xiawan.XXMainApplication;
import com.xiaxiang.xiawan.share.ShareTest;
import com.xiaxiang.xiawan.share.XXShareDialog;
import com.xx.xiawan.net.DGJsonResult;
import com.xx.xiawan.net.DGRequestListener;

import java.util.List;

import com.JSON.MyJsonUtil;
import cn.drj.refreshlayout.BGANormalRefreshViewHolder;
import cn.drj.refreshlayout.BGARefreshLayout;

/**
 * Created by mk on 2017/10/17.
 */

public class FunPhotoFragment extends FragmentBase {
    private View view;
    private GridView fun_photo_list;
    private FunAdapter adapter;
    private TextView text_Tip;
    private View tip_layout;
    private String tRetryText = "点击重试 ";
    private Wave mWaveDrawable;
    private DGPhotoViewDlg photoViewDlg;
    private RxDialogLoading dialogLoading;
    private Handler mUiHandler;
    private BGARefreshLayout mRefreshLayout;
    private final int MSG_PHOTO_DIALOG_SHOW = 0x001;
    private final int MSG_TIP_DIALOG_HIDE = 0x010;
    private final int MSG_TIP_DIALOG_SHOW = 0x011;
    private final int MSG_DELETE_ITEM = 0x200;
    private final int MSG_DELETE_ITEM_SUCESS = 0x201;
    private final int MSG_DELETE_ITEM_ERROR = 0x202;
    private final int MSG_QUERY_SUCESS = 0x300;
    private final int MSG_QUERY_ERROR = 0x301;
    private final int MSG_QUERY_MORE_SUCESS = 0x302;
    private final int MSG_QUERY_MORE_ERROR = 0x303;
    private TextView TitleBarRigthText;
    private View.OnClickListener retryClickListener;
   // private String userName = XXMainApplication.getInstance().userInfo.getUserName();
    private int pageSize = 6;
    private int pageNo = 1;
    private int pageCount = 1;
    private XXShareDialog mShareDialog;
    private XXMainApplication app;
    private String token;
    private Button btnLogin;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fun_fragment, container, false);
        app = XXMainApplication.getInstance();
        setUiHandler();
        initView();
        setListener();
        adapter = new FunAdapter(getActivity());
        fun_photo_list.setAdapter(adapter);
        mShareDialog = new XXShareDialog(getActivity());
        return view;
    }

    private void initView() {
        TitleBarRigthText = view.findViewById(R.id.TitleBarRigthText);
        ((TextView) view.findViewById(R.id.TitleBarText)).setText("趣拍");
        TitleBarRigthText.setText("创建");
        TitleBarRigthText.setVisibility(View.VISIBLE);
        photoViewDlg = new DGPhotoViewDlg(getActivity());
        dialogLoading = new RxDialogLoading(getActivity());
        fun_photo_list = view.findViewById(R.id.fun_photo_list);
        mRefreshLayout = view.findViewById(R.id.refreshLayout);
        btnLogin = view.findViewById(R.id. btnLogin);
        tip_layout = view.findViewById(R.id.tip_layout);
        text_Tip = view.findViewById(R.id.text_Tip);
        mWaveDrawable = new Wave();
        mWaveDrawable.setBounds(0, 0, 100, 100);
        mWaveDrawable.setColor(getResources().getColor(R.color.default_text));
        token = app.getToken();
        if (app.getIsLogin()) {
            GetListData();
        } else {
//            startLoginActivity();
            text_Tip.setVisibility(View.GONE);
            btnLogin.setVisibility(View.VISIBLE);
        }
    }

    private void setListener() {
        TitleBarRigthText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (btnLogin.getVisibility() != View.VISIBLE) {
                    Intent it = new Intent(getActivity(), FunPhotoCreate.class);
                    startActivityForResult(it, FunPhotoCreate.RES_CODE);
                } else {
                    startLoginActivity();
                }

            }
        });
        fun_photo_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                FunPhotoNetBean.RowsEntity item = adapter.getItem(i);
                sendMessage(MSG_PHOTO_DIALOG_SHOW, item.getUrl());
            }
        });

        fun_photo_list.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
            @Override
            public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo contextMenuInfo) {
                menu.setHeaderTitle("选择操作");
                menu.add(0, 0, 0, "删除该条");
                menu.add(0, 1, 0, "分享该条");
            }
        });

        mRefreshLayout.setDelegate(new BGARefreshLayout.BGARefreshLayoutDelegate() {
            @Override
            public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
                GetListData();
            }

            @Override
            public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
                pageNo++;
                if (pageCount < pageNo) {
                    mRefreshLayout.endLoadingMore();
                    return false;
                }
                GetMoreData();
                return true;
            }
        });
        mRefreshLayout.setRefreshViewHolder(new BGANormalRefreshViewHolder(getActivity(), true));

        retryClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                GetListData();
            }
        };
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startLoginActivity();
            }
        });
    }

    private void setUiHandler() {

        mUiHandler = new Handler() {
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                BaseNetBean baseNetBean;
                switch (msg.what) {
                    case MSG_PHOTO_DIALOG_SHOW:
                        photoViewDlg.setUrl((String) msg.obj);
                        photoViewDlg.show();
                        break;
                    case MSG_TIP_DIALOG_SHOW:
                        dialogLoading.show();
                        break;
                    case MSG_TIP_DIALOG_HIDE:
                        dialogLoading.hide();
                        break;
                    case MSG_DELETE_ITEM_SUCESS:
                        adapter.removeItem((Integer) msg.obj);
                        dialogLoading.hide();
                        break;

                    case MSG_QUERY_ERROR:
                        Log.i("FunPhotoFragment ", "MSG_QUERY_ERROR" + (String) msg.obj);
                        text_Tip.setText("网络连接失败！\n" + tRetryText);
                        text_Tip.setCompoundDrawables(null, null, null, null);
                        text_Tip.setOnClickListener(retryClickListener);
                        mRefreshLayout.endRefreshing();
                        break;

                    case MSG_QUERY_SUCESS:
                        Log.i("FunPhotoFragment ", "MSG_QUERY_SUCESS" + (String) msg.obj);
                        baseNetBean = MyJsonUtil.parseObject((String) msg.obj, BaseNetBean.class);
                        if (baseNetBean != null) {
                            if (baseNetBean.isSuccess()) {
                                FunPhotoNetBean dateBean = MyJsonUtil.parseObject(baseNetBean.getContent(), FunPhotoNetBean.class);
                                List<FunPhotoNetBean.RowsEntity> data = dateBean.getRows();
                                if (data != null && data.size() > 0) {
                                    tip_layout.setVisibility(View.GONE);
                                    mRefreshLayout.setVisibility(View.VISIBLE);
                                    btnLogin.setVisibility(View.GONE);
                                    pageCount = dateBean.getPageCount();
                                    adapter.setData(data);
                                } else {
                                    text_Tip.setVisibility(View.VISIBLE);
                                    btnLogin.setVisibility(View.GONE);
                                    text_Tip.setText("未创建条目\n");
                                    text_Tip.setCompoundDrawables(null, null, null, null);
                                }
                            } else {
                                ErrorNetBean errorNetBean = MyJsonUtil.parseObject(baseNetBean.getContent(), ErrorNetBean.class);
                                if (errorNetBean.needLogin()) {
                                    text_Tip.setText("请登录！\n" + tRetryText);
                                    text_Tip.setCompoundDrawables(null, null, null, null);
                                    text_Tip.setOnClickListener(retryClickListener);
                                    mRefreshLayout.endRefreshing();
                                    text_Tip.setVisibility(View.GONE);
                                    btnLogin.setVisibility(View.VISIBLE);
//                                    startLoginActivity();
                                } else {
                                    text_Tip.setText("获取数据失败：" + errorNetBean.getErrorMsg() + "\n" + tRetryText);
                                    text_Tip.setCompoundDrawables(null, null, null, null);
                                    text_Tip.setOnClickListener(retryClickListener);
                                    mRefreshLayout.endRefreshing();
                                }
                            }
                        } else {
                            text_Tip.setText("获取数据失败！\n" + tRetryText);
                            text_Tip.setCompoundDrawables(null, null, null, null);
                            text_Tip.setOnClickListener(retryClickListener);
                        }
                        mRefreshLayout.endRefreshing();
                        break;
                    case MSG_QUERY_MORE_SUCESS:
                        Log.i("FunPhotoFragment ", "MSG_QUERY_SUCESS" + (String) msg.obj);
                        baseNetBean = MyJsonUtil.parseObject((String) msg.obj, BaseNetBean.class);
                        if (baseNetBean != null) {
                            if (baseNetBean.isSuccess()) {
                                FunPhotoNetBean dateBean = MyJsonUtil.parseObject(baseNetBean.getContent(), FunPhotoNetBean.class);
                                List<FunPhotoNetBean.RowsEntity> data = dateBean.getRows();
                                if (data != null && data.size() > 0) {
                                    adapter.addMoreData(data);
                                } else {
                                    pageNo--;
                                }
                            }else {
                                pageNo--;
                            }
                        } else {
                            pageNo--;
                        }
                        mRefreshLayout.endRefreshing();
                        break;

                    default:
                        break;
                }
            }
        };
    }

    private void sendMessage(int what, Object obj) {
        Message msg = mUiHandler.obtainMessage();
        msg.what = what;
        if (obj != null)
            msg.obj = obj;
        mUiHandler.sendMessage(msg);
    }

    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        final int position = info.position;
        Log.i("drj", "pos:" + position);
        switch (item.getItemId()) {
            case 0:
                final RxDialogSureCancel rxDialogSureCancel = new RxDialogSureCancel(getActivity(), R.layout.dialog_makesure);//提示弹窗
                rxDialogSureCancel.setContent("确认要删除吗？");
                rxDialogSureCancel.getSureView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        sendMessage(MSG_TIP_DIALOG_SHOW, position);
                        FunPhotoNetBean.RowsEntity itemPhotoBean = adapter.getItem(position);
                        String url = XXConstants.URI_DEL_FUN_PHOTO + "?id=" + itemPhotoBean.getId();
                        ARCloudEditor.Delete(getActivity(), url, token, new DGRequestListener() {
                            @Override
                            public void onSuccess(DGJsonResult result) {
                                sendMessage(MSG_DELETE_ITEM_SUCESS, position);
                                showToastTips("删除成功! ");
                            }

                            @Override
                            public void onError(String error) {
                                sendMessage(MSG_TIP_DIALOG_HIDE, null);
                                showToastTips("删除失败： " + error);
                            }
                        });
                        rxDialogSureCancel.cancel();
                    }
                });
                rxDialogSureCancel.getCancelView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        rxDialogSureCancel.cancel();
                    }
                });
                rxDialogSureCancel.show();
                Log.i("drj", "0: " + position);
                return true;
            case 1:
                FunPhotoNetBean.RowsEntity itemPhotoBean1 = adapter.getItem(position);
                ShareData shareData = new ShareData();
                shareData.mShareStyle = ShareTest.IMAGEURL;
                shareData.mShareTitle = "扫描一下图片有以外惊喜！";
                shareData.mShareUrl = itemPhotoBean1.getUrl();
                mShareDialog.setShareData(shareData);
                mShareDialog.showDialog();
                return true;
            default:
                return super.onContextItemSelected(item);
        }
    }

    void GetListData() {
        pageNo = 1;
        tip_layout.setVisibility(View.VISIBLE);
        mRefreshLayout.setVisibility(View.GONE);
        text_Tip.setCompoundDrawables(null, mWaveDrawable, null, null);
        text_Tip.setText("正在加载.....");
        text_Tip.setOnClickListener(null);
        token = app.getToken();
        String url = XXConstants.URI_GET_FUN_PHOTO_LIST_BY_USER + "?pageNo=" + pageNo + "&pageSize=" + pageSize + "&userName=" + app.getUserName();

        ARCloudEditor.Query(getActivity(), url, token, new MyHttpUtils.IMyHttpUtilsCallback() {
            @Override
            public void onFailure(String errorMsg) {
                sendMessage(MSG_QUERY_ERROR, errorMsg);
            }

            @Override
            public void onResponse(String response) {
                sendMessage(MSG_QUERY_SUCESS, response);
            }
        });
    }

    void GetMoreData() {
        token = app.getToken();
        String url = XXConstants.URI_GET_FUN_PHOTO_LIST_BY_USER + "?pageNo=" + pageNo + "&pageSize=" + pageSize + "&userName=" + app.getUserName();
        ARCloudEditor.Query(getActivity(), url, token, new MyHttpUtils.IMyHttpUtilsCallback() {
            @Override
            public void onFailure(String errorMsg) {
                mRefreshLayout.endLoadingMore();
                sendMessage(MSG_QUERY_MORE_ERROR, errorMsg);
            }

            @Override
            public void onResponse(String response) {
                sendMessage(MSG_QUERY_MORE_SUCESS, response);
                mRefreshLayout.endLoadingMore();
            }
        });
    }

    public void onResume() {
        super.onResume();
        mWaveDrawable.start();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(!hidden) {
//            if (app.getIsLogin()) {
                GetListData();
//            } else {
//                text_Tip.setText("请登录！\n" + tRetryText);
//                text_Tip.setCompoundDrawables(null, null, null, null);
//                text_Tip.setOnClickListener(retryClickListener);
//                mRefreshLayout.endRefreshing();
//                text_Tip.setVisibility(View.GONE);
//                btnLogin.setVisibility(View.VISIBLE);
//            }
        }
    }


    @Override
    public void onStop() {
        super.onStop();
        mWaveDrawable.stop();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case FunPhotoCreate.RES_CODE:
                if (data != null) {
                    String res = data.getStringExtra("item");
                    token = app.getToken();
                    GetListData();
                }
                break;
            case XXConfigData.LOGIN_REQUEST_CODE:
                if (resultCode == XXConfigData.LOGIN_RECODE_SUCCESS) {

                    token = app.getToken();
                    GetListData();
                } else {
                }
                break;

            default:
                break;
        }
    }
}
